<template>
  <el-dialog
    title="签到审计日志"
    :visible.sync="visible"
    width="90%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @closed="dialogClosed"
  >
    <!-- 查询条件 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="操作类型">
          <el-select v-model="searchForm.operation" placeholder="请选择操作类型" clearable>
            <el-option label="手动签到" value="MANUAL_SIGN"></el-option>
            <el-option label="批量签到" value="BATCH_SIGN"></el-option>
            <el-option label="补签操作" value="MAKEUP_SIGN"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作人">
          <el-input v-model="searchForm.operatorName" placeholder="请输入操作人姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="目标老师">
          <el-input v-model="searchForm.targetName" placeholder="请输入老师姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="操作结果">
          <el-select v-model="searchForm.success" placeholder="请选择操作结果" clearable>
            <el-option label="成功" :value="true"></el-option>
            <el-option label="失败" :value="false"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getDataList" :loading="dataListLoading">
            <i class="el-icon-search"></i> 查询
          </el-button>
          <el-button @click="resetSearch">
            <i class="el-icon-refresh"></i> 重置
          </el-button>
          <el-button type="success" @click="exportLogs" :loading="exportLoading">
            <i class="el-icon-download"></i> 导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section" v-if="statsData">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-number">{{ statsData.totalOperations || 0 }}</div>
            <div class="stat-label">总操作数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card success">
            <div class="stat-number">{{ statsData.successOperations || 0 }}</div>
            <div class="stat-label">成功操作</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card error">
            <div class="stat-number">{{ statsData.failedOperations || 0 }}</div>
            <div class="stat-label">失败操作</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card info">
            <div class="stat-number">{{ statsData.todayOperations || 0 }}</div>
            <div class="stat-label">今日操作</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      style="width: 100%;"
      size="mini"
    >
      <el-table-column prop="operationTime" label="操作时间" width="160" sortable>
        <template slot-scope="scope">
          {{ $moment(scope.row.operationTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
      </el-table-column>
      <el-table-column prop="operation" label="操作类型" width="100">
        <template slot-scope="scope">
          <el-tag :type="getOperationTagType(scope.row.operation)" size="mini">
            {{ getOperationLabel(scope.row.operation) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="operatorName" label="操作人" width="100"></el-table-column>
      <el-table-column prop="targetName" label="目标老师" width="100"></el-table-column>
      <el-table-column prop="success" label="操作结果" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.success ? 'success' : 'danger'" size="mini">
            {{ scope.row.success ? '成功' : '失败' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="reason" label="操作原因" min-width="120" show-overflow-tooltip></el-table-column>
      <el-table-column prop="ipAddress" label="IP地址" width="120"></el-table-column>
      <el-table-column label="操作详情" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="showDetail(scope.row)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
      style="margin-top: 20px; text-align: right;"
    >
    </el-pagination>

    <!-- 详情对话框 -->
    <el-dialog
      title="操作详情"
      :visible.sync="detailVisible"
      width="60%"
      append-to-body
    >
      <div v-if="currentDetail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="操作时间">
            {{ $moment(currentDetail.operationTime).format('YYYY-MM-DD HH:mm:ss') }}
          </el-descriptions-item>
          <el-descriptions-item label="操作类型">
            <el-tag :type="getOperationTagType(currentDetail.operation)" size="mini">
              {{ getOperationLabel(currentDetail.operation) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="操作人">
            {{ currentDetail.operatorName }}
          </el-descriptions-item>
          <el-descriptions-item label="目标老师">
            {{ currentDetail.targetName }}
          </el-descriptions-item>
          <el-descriptions-item label="操作结果">
            <el-tag :type="currentDetail.success ? 'success' : 'danger'" size="mini">
              {{ currentDetail.success ? '成功' : '失败' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="IP地址">
            {{ currentDetail.ipAddress }}
          </el-descriptions-item>
          <el-descriptions-item label="操作原因" :span="2">
            {{ currentDetail.reason || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="错误信息" :span="2" v-if="!currentDetail.success">
            <el-alert :title="currentDetail.errorMessage" type="error" :closable="false"></el-alert>
          </el-descriptions-item>
        </el-descriptions>
        
        <div style="margin-top: 20px;">
          <h4>操作前数据</h4>
          <el-input
            type="textarea"
            :rows="4"
            :value="formatJsonData(currentDetail.beforeData)"
            readonly
          ></el-input>
        </div>
        
        <div style="margin-top: 20px;">
          <h4>操作后数据</h4>
          <el-input
            type="textarea"
            :rows="4"
            :value="formatJsonData(currentDetail.afterData)"
            readonly
          ></el-input>
        </div>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { getSignAuditLogList, getSignAuditStats, exportSignAuditLog } from '@/api/campus/trainSignAuditLog'

export default {
  data() {
    return {
      visible: false,
      detailVisible: false,
      currentDetail: null,
      dataList: [],
      pageIndex: 1,
      pageSize: 20,
      totalPage: 0,
      dataListLoading: false,
      exportLoading: false,
      statsData: null,
      searchForm: {
        operation: '',
        operatorName: '',
        targetName: '',
        success: null,
        dateRange: []
      }
    }
  },
  methods: {
    init() {
      this.visible = true
      this.resetSearch()
      this.getDataList()
      this.getStats()
    },
    
    async getDataList() {
      this.dataListLoading = true
      try {
        const params = {
          page: this.pageIndex,
          limit: this.pageSize,
          operation: this.searchForm.operation,
          operatorName: this.searchForm.operatorName,
          targetName: this.searchForm.targetName,
          success: this.searchForm.success
        }
        
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.startTime = this.searchForm.dateRange[0]
          params.endTime = this.searchForm.dateRange[1]
        }
        
        const { data } = await getSignAuditLogList(params)
        this.dataList = data.list || []
        this.totalPage = data.total || 0
      } catch (error) {
        console.error('获取审计日志失败:', error)
        this.$message.error('获取审计日志失败')
      } finally {
        this.dataListLoading = false
      }
    },
    
    async getStats() {
      try {
        const params = {}
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.startTime = this.searchForm.dateRange[0]
          params.endTime = this.searchForm.dateRange[1]
        }
        
        const { data } = await getSignAuditStats(params)
        this.statsData = data
      } catch (error) {
        console.error('获取统计信息失败:', error)
      }
    },
    
    resetSearch() {
      this.searchForm = {
        operation: '',
        operatorName: '',
        targetName: '',
        success: null,
        dateRange: []
      }
      this.pageIndex = 1
    },
    
    async exportLogs() {
      this.exportLoading = true
      try {
        const params = {
          operation: this.searchForm.operation,
          operatorName: this.searchForm.operatorName,
          targetName: this.searchForm.targetName,
          success: this.searchForm.success
        }
        
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.startTime = this.searchForm.dateRange[0]
          params.endTime = this.searchForm.dateRange[1]
        }
        
        const response = await exportSignAuditLog(params)
        
        // 创建下载链接
        const blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `签到审计日志_${this.$moment().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`
        link.click()
        window.URL.revokeObjectURL(url)
        
        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        this.$message.error('导出失败')
      } finally {
        this.exportLoading = false
      }
    },
    
    showDetail(row) {
      this.currentDetail = row
      this.detailVisible = true
    },
    
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    
    getOperationTagType(operation) {
      const typeMap = {
        'MANUAL_SIGN': 'primary',
        'BATCH_SIGN': 'success',
        'MAKEUP_SIGN': 'warning'
      }
      return typeMap[operation] || 'info'
    },
    
    getOperationLabel(operation) {
      const labelMap = {
        'MANUAL_SIGN': '手动签到',
        'BATCH_SIGN': '批量签到',
        'MAKEUP_SIGN': '补签操作'
      }
      return labelMap[operation] || operation
    },
    
    formatJsonData(jsonStr) {
      try {
        const obj = JSON.parse(jsonStr)
        return JSON.stringify(obj, null, 2)
      } catch (error) {
        return jsonStr || '无数据'
      }
    },
    
    dialogClosed() {
      this.dataList = []
      this.statsData = null
      this.currentDetail = null
      this.resetSearch()
    }
  }
}
</script>

<style scoped>
.search-section {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 20px;
  text-align: center;
  transition: all 0.3s;
}

.stat-card:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.stat-card.success {
  border-left: 4px solid #67c23a;
}

.stat-card.error {
  border-left: 4px solid #f56c6c;
}

.stat-card.info {
  border-left: 4px solid #409eff;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}
</style>